package com.ic.es.service.impl;

import IC.common.core.domain.R;
import com.alibaba.fastjson.JSONObject;
import com.ic.domain.HolographicFileDTO;
import com.ic.domain.HolographicFileVO;
import com.ic.es.result.PageResult;
import com.ic.es.service.EsHolographicFileService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;

@Service
public class EsHolographicFileServiceImpl implements EsHolographicFileService {


    private RestHighLevelClient restHighLevelClient;

    private final static String INDEX_NAME="car";


    @Override
    public R<PageResult<HolographicFileVO>> search(HolographicFileDTO holographicFileDTO) {
        long total=0;
        ArrayList<HolographicFileVO> holographicFileList =  new ArrayList<>();
        SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if(holographicFileDTO.getKeyword()!=null){
            boolQueryBuilder.must(QueryBuilders.matchQuery("brandId",holographicFileDTO.getKeyword()));
        }
        searchSourceBuilder.query(boolQueryBuilder);
        searchSourceBuilder.from((holographicFileDTO.getPageNum()-1)*holographicFileDTO.getPageSize());
        searchSourceBuilder.size(holographicFileDTO.getPageSize());
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = searchResponse.getHits();
            total = hits.getTotalHits().value;
            SearchHit[] searchHits = hits.getHits();
            for (SearchHit searchHit : searchHits) {
                String sourceAsString = searchHit.getSourceAsString();
                HolographicFileVO htmlFileVO =  JSONObject.parseObject(sourceAsString, HolographicFileVO.class);
                holographicFileList.add(htmlFileVO);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.ok(PageResult.toPageResult(total,holographicFileList));
    }

}
